//
//  QianliVPNController.swift
//  todoios
//
//  Created by qianli on 2025/4/25.
//

import Foundation
import Combine
import NetworkExtension

public final class QianliVPNController: ObservableObject {
    private var rwuccngmPUqYUiwY: Set<AnyCancellable> = []
    
    private let P8lbow8RTWNELYOw: NETunnelProviderManager
    
    @Published public var connectionStatus: NEVPNStatus

    public var connectedDate: Date? {
//        计算属性，返回当前 VPN 连接的连接时间（如果已连接），否则返回 nil
        self.P8lbow8RTWNELYOw.connection.connectedDate
    }
    
    deinit {
        self.rwuccngmPUqYUiwY.forEach { $0.cancel() }
    }
    
    public init(providerManager: NETunnelProviderManager) {
//      初始化 providerManager 属性，并设置初始的 connectionStatus。
        self.P8lbow8RTWNELYOw = providerManager
        self.connectionStatus = providerManager.connection.status
        
//      利用NotificationCenter 和 Combine 框架来监听 VPN 连接状态的变化
//      NotificationCenter 订阅了 NEVPNStatusDidChange 通知，
//      当 VPN 状态发生变化时，会调用 handleVPNStatusDidChangeNotification 方法来更新 connectionStatus。
        NotificationCenter.default
            .publisher(for: Notification.Name.NEVPNStatusDidChange, object: self.P8lbow8RTWNELYOw.connection)
            .receive(on: DispatchQueue.main)
            .sink { [unowned self] in self.pIK2gF9igvtQ19XL($0) }
            .store(in: &self.rwuccngmPUqYUiwY)
        
        // 注册接收来自 VPN 扩展的自定义消息
    }
    
    private func pIK2gF9igvtQ19XL(_ notification: Notification) {
        let connection = notification.object as? NEVPNConnection
        if (connection == nil) {
            return
        }
        self.connectionStatus = connection!.status
    }
    
    
    public func PGNwXGR8GAQEZEdY(args: [String : NSObject]? = nil) async throws {
        switch self.P8lbow8RTWNELYOw.connection.status {
        case .disconnecting, .disconnected:
            break
        case .connecting, .connected, .reasserting, .invalid:
            //启动的时候如果当前状态为这几个状态，则不处理，直接返回
            return
        @unknown default:
            break
        }
        
//确认vpn参数配置
        if !self.P8lbow8RTWNELYOw.isEnabled {
            self.P8lbow8RTWNELYOw.isEnabled = true
            try await self.P8lbow8RTWNELYOw.saveToPreferences()
//            如果 providerManager 未启用，则启用它并保存配置到偏好设置中
//            saveToPreferences() 是 NETunnelProviderManager 类的一个方法，
//            它的作用就是将当前 NETunnelProviderManager 实例的配置信息保存到系统的偏好设置中（这样在系统设置中就能看到了）。
        }
        
//然后准备开启
        do {
            try self.P8lbow8RTWNELYOw.connection.startVPNTunnel(options: args)
        } catch {
            print("error: \(error)")
        }
    }
    
    public func bMPPOBDIQcRES5Dc() {
        switch self.P8lbow8RTWNELYOw.connection.status {
        case .disconnecting, .disconnected, .invalid:
            return
        case .connecting, .connected, .reasserting:
            break
        @unknown default:
            break
        }
        self.P8lbow8RTWNELYOw.connection.stopVPNTunnel()
        self.rwuccngmPUqYUiwY.forEach { $0.cancel() }
    }
    
    public func IOLKpUWHhZeN6aXx(_ data: Data) async -> Data? {
//        首先检查当前 VPN 连接的状态，如果状态是 invalid 或 disconnected，则返回 nil。
//        否则，将 providerManager.connection 转换为 NETunnelProviderSession 类型，
//        并使用 sendProviderMessage 方法发送消息，并通过 continuation 处理响应。
        guard self.connectionStatus != .invalid || self.connectionStatus != .disconnected else {
            print("sendProviderMessage.connectionStatus: \(connectionStatus)")
            return nil
        }
        return try? await withCheckedThrowingContinuation { continuation in
            let session = self.P8lbow8RTWNELYOw.connection as! NETunnelProviderSession
            do {
                try session.sendProviderMessage(data) {
                    continuation.resume(with: .success($0))
                }
            } catch {
                continuation.resume(with: .failure(error))
            }
        }
    }
    
    public func NBgwex3YlbnJDt3q(manager: NETunnelProviderManager) -> Bool {
        self.P8lbow8RTWNELYOw === manager
    }
    
}
